import 'package:flutter/material.dart';
import 'dart:ui' as ui;

/// 自定义绘制文字的Widget，集成动画功能
class CustomTextPainter extends StatefulWidget {
  final String text;
  final double mScreenW;
  final TextStyle textStyle;
  final Duration animationDuration;
  final VoidCallback? onAnimationComplete;

  const CustomTextPainter({
    Key? key,
    required this.text,
    required this.mScreenW,
    this.textStyle = const TextStyle(
      fontSize: 24,
      color: Colors.black,
      fontWeight: FontWeight.normal,
    ),
    this.animationDuration = const Duration(seconds: 6),
    this.onAnimationComplete,
  }) : super(key: key);

  @override
  _CustomTextPainterState createState() =>
      _CustomTextPainterState(mScreenW: mScreenW);
}

class _CustomTextPainterState extends State<CustomTextPainter>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Offset> _animation;
  double mScreenW = 0;

  _CustomTextPainterState({
    required this.mScreenW
  });

  @override
  void initState() {
    super.initState();
    _initializeAnimation();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  /// 计算文本实际显示宽度
  double _calculateTextWidth() {
    final textPainter = TextPainter(
      text: TextSpan(
        text: widget.text,
        style: widget.textStyle,
      ),
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.width;
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        print("约束信息: ${constraints}");
        return AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return Transform.translate(
              offset: _animation.value,
              child: _TextPainterWidget(
                text: widget.text,
                textStyle: widget.textStyle,
              ),
            );
          },
        );
      },);
  }

  void _initializeAnimation() {
    _controller = AnimationController(
      duration: widget.animationDuration,
      vsync: this,
    );

    _animation = Tween<Offset>(
      begin: Offset(mScreenW, 0), // 从屏幕右侧开始
      end: Offset(-_calculateTextWidth(), 0.0), // 移动到屏幕左侧之外
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.linear));

    _controller.forward().whenComplete(() {
      if (mounted) {
        widget.onAnimationComplete?.call();
      }
    });
  }
}

/// 实际的文本绘制Widget
class _TextPainterWidget extends StatelessWidget {
  final String text;
  final TextStyle textStyle;

  const _TextPainterWidget({
    Key? key,
    required this.text,
    required this.textStyle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: const Size(double.infinity, 20),
      painter: TextCustomPainter(text, textStyle,getTopPositionInParent(context)),
    );
  }
  double getTopPositionInParent(BuildContext context) {
    try {
      final RenderBox renderBox = context.findRenderObject() as RenderBox;
      final position = renderBox.localToGlobal(Offset.zero);
      return position.dy;
    } catch (e) {
      return 0.0;
    }
  }
}

/// 自定义Painter类，负责实际的文字绘制
class TextCustomPainter extends CustomPainter {
  final String text;
  final TextStyle textStyle;
  final double topOffset;

  TextCustomPainter(this.text, this.textStyle, this.topOffset);

  @override
  void paint(Canvas canvas, Size size) {
    // 创建文本画笔
    final textPainter = TextPainter(
      text: TextSpan(
        text: text,
        style: textStyle,
      ),
      textDirection: TextDirection.ltr,
    );

    // 布局文本，使用无限宽度以适应长文本
    textPainter.layout(minWidth: 0, maxWidth: double.infinity);

    // 设置画布大小为文本实际大小
    canvas.save();
    canvas.clipRect(Rect.fromLTWH(0, 0, textPainter.width, textPainter.height));

    print(topOffset);
    // 绘制文本
    textPainter.paint(canvas, Offset(0, 0));

    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  @override
  Size get size {
    final textPainter = TextPainter(
      text: TextSpan(text: text, style: textStyle),
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(minWidth: 0, maxWidth: double.infinity);
    return Size(textPainter.width, textPainter.height);
  }
}

/// 示例使用页面
class CustomTextViewExample extends StatefulWidget {
  @override
  _CustomTextViewExampleState createState() => _CustomTextViewExampleState();
}

class _CustomTextViewExampleState extends State<CustomTextViewExample> {
  List<Map<String, dynamic>> animatedTexts = [];
  int textId = 0;

  void _addAnimatedText() {
    setState(() {
      final id = ++textId;
      animatedTexts.add({
        'id': id,
        'text': '这是一条很长的飘条文本，用来测试超长文本的显示效果 $id',
      });
    });
  }

  void _removeText(int id) {
    setState(() {
      animatedTexts.removeWhere((item) => item['id'] == id);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Custom Text Painter'),
      ),
      body: Stack(
        children: [
          Center(
            child: ElevatedButton(
              onPressed: _addAnimatedText,
              child: Text('添加飘条动画'),
            ),
          ),
          Positioned(
            top: 100,
            left: 0,
            right: 0,
            height: 300,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: animatedTexts.map((item) {
                return CustomTextPainter(
                  text: item['text'],
                  mScreenW: MediaQuery
                      .of(context)
                      .size
                      .width,
                  textStyle: TextStyle(
                    fontSize: 20,
                    color: Colors.blue,
                    fontWeight: FontWeight.bold,
                  ),
                  animationDuration: Duration(seconds: 5),
                  onAnimationComplete: () => _removeText(item['id']),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: CustomTextViewExample(),
  ));
}
